from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from models import *
from xml.dom import minidom
import logging
class GetIcon(webapp.RequestHandler):
        """
        Displays an item icon. 
        If it is not found from the database, then it is fetched from wowarmory.com 
        and saved to DB
        """
        def get(self):
                icon_id = self.request.get("i")
                result = IconCache.get_by_key_name(icon_id)
                #result = db.GqlQuery("SELECT * FROM IconCache WHERE icon_id = :1 LIMIT 1", icon_id).fetch(1)
                self.response.headers['Content-Type'] = 'image/png'
                if result is not None:
                    self.response.out.write(result.blob)
                else:
                    icon_url = "http://www.wowarmory.com/wow-icons/_images/21x21/"+icon_id+".png"
                    resp = urlfetch.fetch(icon_url)
                    if resp.status_code == 200:
                        icon = IconCache(key_name=icon_id)
                        icon.icon_id = icon_id
                        icon.blob = db.Blob(resp.content)
                        icon.put()
                        self.response.out.write(icon.blob)

def GetGemInfo(gemid):
    """GetGemInfo(gemid)
        Returns a wowhead link to the gemId with name and such! if gemid is <=0 returns 0 """
    if gemid > 0:
        result = GemCache.get_by_key_name(gemid)
        if result is not None:
            return result.data
        else:
            url = "http://www.wowhead.com/?item="+gemid+"&xml"
            resp = urlfetch.fetch(url,headers = {'User-Agent':"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.2) Gecko/20070319 Firefox/2.0.0.3"})
            if resp.status_code == 200:
                content = minidom.parseString(resp.content)
                if len(content.getElementsByTagName("name")) > 0 and len(content.getElementsByTagName("quality")) > 0 and len(content.getElementsByTagName("link")) > 0:
                    name = content.getElementsByTagName("name")[0]
                    quality = content.getElementsByTagName("quality")[0]
                    link = content.getElementsByTagName("link")[0]
                    data = '<a href="'+link.firstChild.data+'" class="wowhead qu'+quality.getAttribute('id')+'">'+name.firstChild.data+'</a><br>'
                    gem = GemCache(key_name=gemid)
                    gem.data = data
                    gem.put()
                    return data
    else:
        return 0

class ItemToolTip(webapp.RequestHandler):
    useragent =  "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.2) Gecko/20070319 Firefox/2.0.0.3"
    def  get(self):
        region = self.request.get('a',default_value="eu")
        realm = self.request.get('r')
        name = self.request.get('n')
        item_id = self.request.get('i')
        item_slot = self.request.get('s')
        gems = self.request.get('g').split(',')
        data = memcache.get(region+realm+name+item_id)
        if data is None:
            url = "http://"+region+".wowarmory.com/item-tooltip.xml?r="+realm+"&n="+name+"&s="+item_slot+"&i="+item_id
            try:
                response = urlfetch.fetch(url, headers = {'User-Agent': self.useragent})
            except urlfetch.DownloadError:
		self.response.out.write("Error loading item tooltip")
            if response.status_code == 200:
                content = minidom.parseString(response.content)
                quality = content.getElementsByTagName("overallQualityId")[0].firstChild.data
                enchant = content.getElementsByTagName("enchant")
                name = content.getElementsByTagName("name")[0].firstChild.data
                data = '<a class="wowhead qu'+quality+'" href="http://wowhead.com/?item='+item_id+'">'+name+' &gt;</a><br>'
                if enchant:
                    enchant = enchant[0].firstChild.data
                    data += enchant +"<br>"
                gemdata = ""
                for gem in gems:
                    if int(gem) > 0:
                        gemdata += GetGemInfo(gem)               
                data += gemdata
                    
            if not memcache.add(region+realm+name+item_id,data,time=3600):
                if not memcache.replace(region+realm+name+item_id,data,time=3600):
                    logging.error("Memcache set failed...")
        self.response.out.write(data)
        
